<template>
  <div class="ms-list">
    <el-row class="operation">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">
          <icon style="" name="home"></icon>
        </el-breadcrumb-item>
        <el-breadcrumb-item>渠道推广系统</el-breadcrumb-item>
        <el-breadcrumb-item>留言板</el-breadcrumb-item>
        <el-breadcrumb-item>列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button-group>
        <el-button type="primary" size="small" @click="addRow()">
          <icon name="cloud-download"/>&nbsp;&nbsp;留言导出
        </el-button>
      </el-button-group>
    </el-row>

    <ms-slide
      :title="row.title"
      :width="500"
      ref="slideModifyRow">
      <el-form class="form" label-width="120px" size="small" :model="row.form" ref="formModifyRow">
        <el-form-item label="起止日期" :rules="[{required: true, message: '请选择起止日期'}]">
          <el-col>
            <el-date-picker
              v-model="row.form.date"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="mini"
              :value-format="row.format"
              clearable>
            </el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="导出项目" prop="id" :rules="[{required: true, message: '请选择导出项目'}]">
          <el-select v-model="row.form.id">
            <template v-for="item in items">
              <el-option :label="item.title" :value="item.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="已读状态" prop="readStatus" :rules="[{required: true, message: '请选择已读状态'}]">
          <el-select v-model="row.form.readStatus">
            <el-option label="不限" :value="-1"></el-option>
            <el-option label="未读" :value="0"></el-option>
            <el-option label="已读" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导出格式" prop="fileGenre" :rules="[{required: true, message: '请选择导出格式'}]">
          <el-select v-model="row.form.fileGenre">
            <el-option label="CSV格式" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportFile()">导出</el-button>
          <el-button @click="resetForm('formModifyRow')">重置</el-button>
        </el-form-item>
      </el-form>
    </ms-slide>

    <ms-search :data="search.list" @click="updateConditions"></ms-search>

    <el-table
      v-loading="table.loading"
      class="element-table"
      size="small"
      stripe border
      :data="table.list"
      :highlight-current-row="true"
      :fit="true">
      <el-table-column type="expand" min-width="20">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="table-expand">
            <el-form-item label="联系人">
              <span>{{ scope.row.contacts }}</span>
            </el-form-item>
            <el-form-item label="身份证">
              <span>{{ scope.row.idCard }}</span>
            </el-form-item>
            <el-form-item label="手机">
              <span>{{ scope.row.mobile }}</span>
            </el-form-item>
            <el-form-item label="电话">
              <span>{{ scope.row.phone }}</span>
            </el-form-item>
            <el-form-item label="QQ">
              <span>{{ scope.row.qq }}</span>
            </el-form-item>
            <el-form-item label="地址">
              <span>{{ scope.row.address }}</span>
            </el-form-item>
            <el-form-item label="IP地区">
              <span>{{ scope.row.ipArea }}</span>
            </el-form-item>
            <el-form-item label="留言内容" class="content">
              <span>{{ scope.row.content }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="ID" prop="id" min-width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.readStatus === 0">
            <img src="../../../../static/images/unread.png" height="13" alt="未读"/>
          </span>
          <template>{{scope.row.id}}</template>
        </template>
      </el-table-column>
      <el-table-column label="项目" prop="itemTitle">
        <template slot-scope="scope">
          <el-tooltip effect="dark" :content="scope.row.customerTitle" placement="top">
            <span>{{scope.row.itemTitle}}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="客户端" prop="clientId" min-width="50">
        <template slot-scope="scope">
          <ms-device :client-id="scope.row.clientId"></ms-device>
        </template>
      </el-table-column>
      <el-table-column label="来自" prop="genreTitle" min-width="80">
        <template slot-scope="scope">
          <el-tooltip effect="dark" :content="scope.row.templateStyleTitle" placement="top">
            <span>{{scope.row.genreTitle}}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="时间" prop="publishTime" min-width="140"/>
      <el-table-column label="搜索词" prop="searchWord">
        <template slot-scope="scope">
          <el-popover
            placement="top-start"
            width="380">
            <el-button slot="reference" type="text" size="small">{{scope.row.searchWord}}</el-button>
            <table class="ms-table">
              <tbody>
              <tr>
                <td class="left" style="width: 60px;"><strong>搜索引擎</strong></td>
                <td class="left">{{scope.row.searchTitle}}</td>
              </tr>
              <tr>
                <td class="left"><strong>搜索词</strong></td>
                <td class="left">{{scope.row.searchWord}}</td>
              </tr>
              <tr>
                <td class="left"><strong>来源页</strong></td>
                <td class="left">
                  <a :href="scope.row.referrerUrl" target="_blank">{{scope.row.referrerUrlView}}</a>
                </td>
              </tr>
              <tr>
                <td class="left"><strong>着路页</strong></td>
                <td class="left">
                  <a :href="scope.row.pageUrl" target="_blank">{{scope.row.pageUrl}}</a>
                </td>
              </tr>
              </tbody>
            </table>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="问卷" prop="questionnaire" min-width="50">
        <template slot-scope="scope">
          <el-popover
            v-if="scope.row.openQuestionnaireId > 0"
            placement="top-start"
            width="380"
            @show="showQuestionnaire(scope.$index)">
            <el-button slot="reference" type="text" size="small">已填</el-button>
            <table class="ms-table ms-table-striped">
              <thead>
              <tr>
                <th>问题</th>
                <th>用户回答</th>
              </tr>
              </thead>
              <tbody>
              <tr v-for="(questionnaire, index) in row.questionnaire" :key="index">
                <td class="left">{{questionnaire.title}}</td>
                <td class="left">{{questionnaire.answer}}</td>
              </tr>
              </tbody>
            </table>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" min-width="80" class-name="option">
        <template slot-scope="scope">
          <template v-if="scope.row.status > -1">
            <ms-confirm-button v-if="scope.row.status > -1" title="删除" @confirm="deleteRow(scope.$index)">
              <p>您确定要删除<code>id = {{scope.row.id}}</code>的数据吗？</p>
            </ms-confirm-button>
          </template>

          <ms-confirm-button v-if="scope.row.readStatus === 1" title="设置为未读" @confirm="setting(scope.$index)">
            <p>设置为未读 ？</p>
          </ms-confirm-button>
          <ms-confirm-button v-else-if="scope.row.readStatus === 0" title="设置为已读" @confirm="setting(scope.$index)">
            <p>设置为已读 ？</p>
          </ms-confirm-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      layout="total, sizes, prev, pager, next, jumper"
      :current-page.sync="table.pagination.page"
      :total="table.pagination.totalRow"
      :page-size="table.pagination.pageSize"
      :page-sizes="table.pagination.pageSizes"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>

<script>
  import MsSearch from '@/components/common/Search.vue'
  import MsConfirmButton from '@/components/common/ConfirmButton.vue'
  import MsDevice from '@/components/common/Device.vue'
  import MsSlide from '@/components/common/Slide.vue'
  import Items from '@/api/customer/items'
  import Api from '@/api/customer/feedback'
  import ResponseParse from '@/utils/response-parse'
  import {
    GENRES, SEARCH_CONDITION, SEARCH_ENGINES,
    TEMPLATE_STYLES
  } from '../../../models/customer/feedbacks'

  export default {
    components: {
      MsSlide,
      MsSearch,
      MsConfirmButton,
      MsDevice
    },
    data () {
      return {
        search: {
          list: [],
          condition: {}
        },
        table: {
          loading: true,
          list: [],
          pagination: {}
        },
        row: {
          questionnaire: [],
          title: '留言导出',
          enabled: false,
          format: 'yyyy-MM-dd',
          form: {
            date: [],
            id: '',
            fileGenre: '',
            readStatus: ''
          }
        },
        items: []
      }
    },
    created () {
      this.search.list = SEARCH_CONDITION

      this.table.loading = true
      this.table.list = []
      this.requestList()
    },
    methods: {
      requestList () {
        let params = Object.assign({}, {page: this.table.pagination.page, pageSize: this.table.pagination.pageSize},
          this.search.condition)
        this.table.loading = true
        Api.list({search: params}, response => {
          let status = response.status || 0
          let body = response.data || []
          if (status === 200 || status === 204) {
            this.table.list = body.map(item => {
              item.genreTitle = item.genreId > 0 && GENRES.hasOwnProperty(item.genreId) ? GENRES[item.genreId] : '其他'
              item.templateStyleTitle = TEMPLATE_STYLES[item.templateStyle] || '自定义模板'

              item.searchTitle = SEARCH_ENGINES[item.searchDomain]

              item.referrerUrlView = item.referrerUrl && item.referrerUrl.length > 100
                ? item.referrerUrl.substr(0, 50) + '...' + item.referrerUrl.substr(-30, 30) : item.referrerUrl

              return item
            })
            this.table.pagination = ResponseParse.pagination(response.headers)
          } else {
            this.table.list = []
          }
          this.table.loading = false
        })
      },
      handleSizeChange (val) {
        this.table.pagination.pageSize = val
        this.requestList()
      },
      handleCurrentChange (val) {
        this.table.pagination.page = val
        this.requestList()
      },
      updateConditions (conditions) {
        this.table.pagination.page = 1

        const time = conditions.time || []
        this.search.condition = Object.assign({}, conditions, {startTime: time[0], endTime: time[1]})
        this.requestList()
      },
      showQuestionnaire (index) {
        const item = this.table.list[index]

        Api.getOpenQuestionnaire({id: item.id}, response => {
          let status = response.status || 0
          let body = response.data || {}
          if (status >= 200 && status <= 204) {
            this.row.questionnaire = JSON.parse(body.content || '[]')
          } else {
            this.row.questionnaire = []
          }
        })
      },
      deleteRow (index) {
        const item = this.table.list[index]
        Api.delete({id: item.id}, response => {
          let status = response.status || 0
          let body = response.data || {}
          if (status >= 200 && status <= 204) {
            this.table.list.splice(index, 1, Object.assign({}, item, {status: -1}))
          } else {
            this.$message.error(body.error || '操作失败')
          }
        })
      },
      setting (index) {
        const item = this.table.list[index]
        if (item.readStatus === 1) {
          Api.unread({id: item.id}, response => {
            let status = response.status || 0
            let body = response.data || {}
            if (status >= 200 && status <= 204) {
              this.table.list[index].readStatus = 0
              this.$message.success('操作成功')
            } else {
              this.$message.error(body.error || '操作失败')
            }
          })
        } else if (item.readStatus === 0) {
          Api.read({id: item.id}, response => {
            let status = response.status || 0
            let body = response.data || {}
            if (status >= 200 && status <= 204) {
              this.table.list[index].readStatus = 1
              this.$message.success('操作成功')
            } else {
              this.$message.error(body.error || '操作失败')
            }
          })
        }
      },
      addRow () {
        this.row.form = {}
        // 获得 所有项目
        Items.getItems(response => {
          let status = response.status || 0
          let body = response.data || []
          if (status >= 200 && status <= 204) {
            this.items = body
          }
        })

        this.showSlide('slideModifyRow')
      },
      exportFile () {
        this.$refs['formModifyRow'].validate((valid) => {
          if (valid) {
            let $data = this.row.form
            let parameters1 = '?startTime=' + $data.date[0] + '&endTime=' + $data.date[1]
            let parameters2 = '&itemId=' + $data.id
            let parameters3 = '&fileGenre=' + $data.fileGenre
            let parameters4 = '&readStatus=' + $data.readStatus

            window.location.href = '/rest/customer/feedback/feedbacks/files' +
              parameters1 + parameters2 + parameters3 + parameters4
          } else {
            return false
          }
        })
      },
      showSlide (ref) {
        this.$refs[ref].show()
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      }
    }
  }
</script>

<style lang="scss">
  @import "../../../assets/styles/env";

  .element-table th {
    height: 48px;
  }

  .table-expand {
    text-align: left;
    label {
      width: 80px;
      line-height: 28px;
      font-weight: bold;
      color: $color-secondary
    }
    .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
      width: calc((100% - 100px) / 2);
      &__content {
        line-height: 28px;
      }
    }
    .content {
      width: 88%;
    }
  }

  .ms-table {
    width: 100%;
    border-collapse: collapse;
    font-size: $size-small;
    line-height: $size-small;
    th {
      padding: 8px 5px;
    }
    td, th {
      border: 1px solid $color-white-tint;
      text-align: center;
      word-break: break-all;
      padding: 5px;
      &.left {
        text-align: left;
      }
      p {
        margin: 2px 0;
      }
      a {
        color: $color-info
      }
    }
    &.ms-table-striped {
      tr:nth-child(even) {
        td {
          background-color: $color-tint;
        }
      }
    }
  }
</style>
